package com.health.tools;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.text.TextUtils;
import android.util.Base64;

public class ImageTools {
	// 判断sd卡的照片文件是不是存在
	public static boolean fileIsExists(String imgPath) {
		File f = new File(imgPath);
		if (!f.exists()) {
			return false;
		}
		return true;
	}

	/**
	 * 加载本地图片
	 * http://bbs.3gstdy.com
	 * @param url
	 * @return
	 */
	public static Bitmap getLoacalBitmap(String url) {
		try {
			FileInputStream fis = new FileInputStream(url);
			return BitmapFactory.decodeStream(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static Bitmap readBitmapAutoSize(String filePath) {
		// outWidth和outHeight是目标图片的最大宽度和高度，用作限制
		Bitmap bm = null;
		try {
			BitmapFactory.Options options = setBitmapOption(filePath);
			bm = BitmapFactory.decodeFile(filePath, options);
			// bm=BitmapFactory.decodeFile(filePath);
			// bm=loadImageFromUrl(bm);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bm;
	}

	private static BitmapFactory.Options setBitmapOption(String file) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inJustDecodeBounds = true;
		// 设置只是解码图片的边距，此操作目的是度量图片的实际宽度和高度
		BitmapFactory.decodeFile(file, opt);
		opt.inDither = false;
		opt.inPreferredConfig = Bitmap.Config.RGB_565;

		// 设置加载图片的颜色数为16bit，默认是RGB_8888，表示24bit颜色和透明通道，但一般用不上
		// opt.inSampleSize = 1;
		opt.inSampleSize = computeSampleSize(opt, -1, 600 * 600);
		opt.inJustDecodeBounds = false;// 最后把标志复原
		return opt;
	}

	public static int computeSampleSize(BitmapFactory.Options options,

	int minSideLength, int maxNumOfPixels) {

		int initialSize = computeInitialSampleSize(options, minSideLength,

		maxNumOfPixels);

		int roundedSize;

		if (initialSize <= 8) {

			roundedSize = 1;

			while (roundedSize < initialSize) {

				roundedSize <<= 1;

			}

		} else {

			roundedSize = (initialSize + 7) / 8 * 8;

		}

		return roundedSize;

	}

	private static int computeInitialSampleSize(BitmapFactory.Options options,

	int minSideLength, int maxNumOfPixels) {

		double w = options.outWidth;
		double h = options.outHeight;
		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
				.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
				Math.floor(w / minSideLength), Math.floor(h / minSideLength));
		if (upperBound < lowerBound) {
			// return the larger one when there is no overlapping zone.
			return lowerBound;

		}

		if ((maxNumOfPixels == -1) &&

		(minSideLength == -1)) {

			return 1;

		} else if (minSideLength == -1) {

			return lowerBound;

		} else {

			return upperBound;

		}

	}

	public static String bitmaptoString(Bitmap bitmap) {

		// int lenstr=bitmap.get
		// bitmap=comp(bitmap);
		// 将Bitmap转换成字符串
		String result = "";
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, 60, bStream);// 原来是60
		byte[] bytes = bStream.toByteArray();
		byte[] bb = BASE64.encode(bytes);
		try {
			result = new String(bb, "UTF-8").replace("+", "%2B");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		}
		// string=Base64.encodeToString(bytes,Base64.DEFAULT);
		return result;
	}

	protected static Bitmap loadImageFromUrl(Bitmap bitmap) {

		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		int newWidth = 768;
		int newHeight = 576;
		if (width > height) {
			newWidth = 768;
			newHeight = 576;
		} else {
			newWidth = 576;
			newHeight = 768;
		}

		// 计算缩放比例
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 取得想要缩放的matrix参数
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// 得到新的图片
		bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
		return bitmap;

	}

	protected Bitmap loadImageFromUrl2(Bitmap bitmap) {

		float count = bitmap.getRowBytes() * bitmap.getHeight();
		// float dianbit=bitmap.getRowBytes()/bitmap.getWidth();
		float setcount = 300 * 1024;
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();

		float sf = setcount / (bitmap.getRowBytes() * height);
		if (count > setcount) {
			// 取得想要缩放的matrix参数
			Matrix matrix = new Matrix();
			matrix.postScale(sf, sf);
			// 得到新的图片
			bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
					true);
		}
		return bitmap;

	}
/**
 * 旋转图片 
 * @param angle
 * @param bitmap
 * @return
 */
	public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
		// 旋转图片 动作
		Matrix matrix = new Matrix();
		matrix.postRotate(angle);
		System.out.println("angle2=" + angle);
		// 创建新的图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
				bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		return resizedBitmap;
	}
	
	/**
	 * 读取图片属性：旋转的角度
	 * @param path 图片绝对路径
	 * @return degree旋转的角度
	 */
    public static int readPictureDegree(String path) {
        int degree  = 0;
        try {
                ExifInterface exifInterface = new ExifInterface(path);
                int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                        degree = 90;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                        degree = 180;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                        degree = 270;
                        break;
                }
        } catch (IOException e) {
                e.printStackTrace();
        }
        return degree;
    }
    /** 
     * bitmap转为base64 
     * @param bitmap 
     * @return 
     */  
    public static String bitmapToBase64(Bitmap bitmap) {  
      
        String result = null;  
        ByteArrayOutputStream baos = null;  
        try {  
            if (bitmap != null) {  
                baos = new ByteArrayOutputStream();  
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
      
                baos.flush();  
                baos.close();  
      
                byte[] bitmapBytes = baos.toByteArray();  
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (baos != null) {  
                    baos.flush();  
                    baos.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return result;  
    }  
      
    /** 
     * base64转为bitmap 
     * @param base64Data 
     * @return 
     */  
    public static Bitmap base64ToBitmap(String base64Data) {  
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);  
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);  
    }

    public static String imageURLToString(String fileURL){
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(fileURL);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[2048];
		int count = 0;
		try {
			while ((count = fis.read(buffer)) >= 0) {
                baos.write(buffer, 0, count);
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		String uploadBuffer = new String(org.kobjects.base64.Base64.encode(baos.toByteArray()));
		return uploadBuffer;
	}

	/**
	 * 将图片转换成Base64编码的字符串
	 */
	public static String imageToBase64(String path){
		if(TextUtils.isEmpty(path)){
			return null;
		}
		InputStream is = null;
		byte[] data = null;
		String result = null;
		try{
			is = new FileInputStream(path);
			//创建一个字符流大小的数组。
			data = new byte[is.available()];
			//写入数组
			is.read(data);
			//用默认的编码格式进行编码
			result = Base64.encodeToString(data,Base64.NO_WRAP);
//			return URLEncoder.encode(result,"UTF-8");
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			if(null !=is){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
		return result;
	}
}
